package com.bwie.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.doamin.dto.BoughtProductDTO;
import com.bwie.common.doamin.dto.ProductDTO;
import com.bwie.common.doamin.model.SysUser;
import com.bwie.common.doamin.vo.ProductVO;
import com.bwie.common.exceptions.BizException;
import com.bwie.common.result.PageResult;
import com.bwie.common.utils.JwtUtils;
import com.bwie.product.es.ProductES;
import com.bwie.product.esMapper.ProductEsMapper;
import com.bwie.product.mapper.ProductMapper;
import com.bwie.product.service.ProductService;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:2943147140@qq.com">刘洋朔</a>
 * @version 1.0
 * @description:
 * @date 2025/9/9 14:23
 */
@Service
public class ProductServiceImpl implements ProductService {
    /**
     * 产品持久层
     */
    @Autowired
    private ProductMapper productMapper;
    /**
     * 产品ES持久层
     */
    @Autowired
    private ProductEsMapper productEsMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取所有产品列表
     * @param productDTO
     * @return
     */
    @Override
    public PageResult<ProductVO> selAllProductList(ProductDTO productDTO) {
        LambdaEsQueryWrapper<ProductES> wrapper = new LambdaEsQueryWrapper<>();
        EsPageInfo<ProductES> productESEsPageInfo = productEsMapper.pageQuery(wrapper, productDTO.getPageNum(), productDTO.getPageSize());
        List<ProductES> esPageInfoList = productESEsPageInfo.getList();
        //转换类型
        List<ProductVO> productVOS = esPageInfoList.stream().map(esPageInfo -> {
            ProductVO productVO = new ProductVO();
            BeanUtil.copyProperties(esPageInfo, productVO);
            productVO.setId(Long.valueOf(esPageInfo.getId()));
            return productVO;
        }).collect(Collectors.toList());
        return PageResult.toPageResult(productESEsPageInfo.getTotal(),productVOS);
    }

    /**
     * 购买商品
     *
     * @param productId
     * @return
     */
    @Override
    public ProductVO echoProduct(Long productId) {
        if(ObjUtil.isEmpty(productId)){
            throw new BizException("产品id不能为空");
        }
        //获取信息
        return productMapper.selProductInfo(productId);
    }

    /**
     * 购买产品
     * @param boughtProductDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void boughtProducts(BoughtProductDTO boughtProductDTO) {
        //防抖
        String token = boughtProductDTO.getToken();
        Boolean hasKey = redisTemplate.hasKey("bought:" + token);
        if(!hasKey){
            throw new BizException("请勿重复操作");
        }
        //下面
        String productName = boughtProductDTO.getProductName();
        Integer num = boughtProductDTO.getNum();
        //获取对弈的产品数量,判断库存
        ProductVO productVO = productMapper.selProductInfoByName(productName);
        if(productVO.getInventory() < num){
            throw new BizException("库存不足啦,我们尽快补货");
        }
        //获取当前登录用户信息
        SysUser currentLoginUserInfo = getCurrentLoginUserInfo();
        Long userId = currentLoginUserInfo.getId();
        boughtProductDTO.setUserId(userId);
        //删除token
        redisTemplate.delete("bought:"+token);
        //添加订单
        productMapper.insertOrder(boughtProductDTO);
        //减库存
        productMapper.lessProductNum(productName,num);
        //修改优惠券状态
        if(ObjUtil.isNotEmpty(boughtProductDTO.getCouponId())){
            productMapper.updateCouponStatus(userId,boughtProductDTO.getCouponId());
        }
    }

    /**
     * 防抖
     */
    @Override
    public String boughtToken() {
        String token = IdUtil.fastSimpleUUID();
        redisTemplate.opsForValue().set("bought:"+token,1);
        return token;
    }


    //获取当前登录用户信息
    private SysUser getCurrentLoginUserInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        if(StrUtil.isBlank(token)){
            throw new BizException("登录超时,请重新登陆");
        }
        String userKey = JwtUtils.getUserKey(token);
        SysUser sysUser = (SysUser) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return sysUser;
    }
}
